
#coding:utf-8
__author__ = 'admin zhoushuang'

from SocketServer import BaseRequestHandler, TCPServer
import os
import os.path
import gvars
import logging
import sys

import modimporter


class ProtocolHandler(BaseRequestHandler, object):
    """ Tcp Protocal Paramters handler.

    Fetch request paramter from tcp socket, then calling handle module to handle request.
    """
    def __init__(self, request, client_address, server):
        super(ProtocolHandler, self).__init__(request, client_address, server)

    def handle(self):
        """ Handler recevied request

        Request Parameter is received, like this, KEY = VALUE pairs

            module = mod_execute
            comdline = echo.bat
            ....
            Gvar.EOFSTRING

        Every line is a Key-Value pair. The ending String is Gvar.EOFSTRING.
        self.ReqDict store request's Key-Values

        :return: None
        """
        logging.info('Get connection from {}'.format(self.client_address))

        mname = b''
        if self.request.recv(len(b'module=')) != b'module=':
            self.request.send('#Error\t first line must be module=module_name\n')
            self.request.send(gvars.EOFSTR + '\n')
            return
        else:
            while True:
                c = self.request.recv(1)
                if c != b'\n':
                    mname += c
                else:
                    break
            mname = bytes(mname)

        logging.info("module {} is going to execute.".format(mname))
        req_dict = {'module': mname}
        # module = globals().get(mname, None)
        module = sys.modules.get(mname, None)
        handler = getattr(module, 'gethandler', None)()
        handler.handle_agent_side(req_dict, self.request)
        return

if __name__ == "__main__":

    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        # filename='/tmp/test.log',
                        filemode='w')

    logging.info("pwd : {}".format(os.getcwd()))
    logging.info('globals modules: {}'.format(globals()))
    logging.info('operaction helpler agentd is started.')
    # print 'pwd: ', os.getcwd()
    # print 'globals modules: ', globals()
    # print 'operation helper: agentd is started.'
    serv = TCPServer(('', gvars.PORT), ProtocolHandler)
    serv.serve_forever()










